/// Upload controller
/// ----------------------------------------------------
/// @Project :   xinhou-rocket-admin
/// @File    :   upload_controller.rs
/// @Contact :   sp_hrz@qq.com
///
/// @Modify Time      @Author    @Version    @Description
/// ------------      -------    --------    -----------
/// 2024/07/04 17:43   shenpeng   1.0         None

use rocket::data::{Data, ToByteUnit};
use rocket::http::Status;
use rocket::response::status;
use rocket::tokio::fs::File;
use rocket::tokio::io::AsyncWriteExt;
use std::path::PathBuf;
use rocket_okapi::openapi;

#[openapi(tag = "文件上传管理")]
#[post("/admin/upload", data = "<data>")]
pub async fn upload(data: Data<'_>) -> Result<status::Custom<String>, status::Custom<String>> {
    let file_path = PathBuf::from("./uploads/uploaded_file.txt");

    // 创建上传目录（如果不存在）
    if let Err(e) = tokio::fs::create_dir_all(file_path.parent().unwrap()).await {
        return Err(status::Custom(Status::InternalServerError, format!("Failed to create uploads directory: {}", e)));
    }

    // 将上传的数据流写入文件
    let mut file = match File::create(&file_path).await {
        Ok(f) => f,
        Err(e) => return Err(status::Custom(Status::InternalServerError, format!("Failed to create file: {}", e))),
    };

    if let Err(e) = data.open(128.kibibytes()).stream_to(&mut file).await {
        return Err(status::Custom(Status::InternalServerError, format!("Failed to write to file: {}", e)));
    }

    Ok(status::Custom(Status::Ok, "File uploaded successfully".into()))
}